<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { computed, reactive, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

// 定义props
interface Props {
  visible: boolean;
  card?: any;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  card: null,
});

// 定义emits
const emit = defineEmits<{
  save: [card: any];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const saving = ref(false);

// 表单数据
const formData = reactive({
  type: '',
  salesCommission: 0,
  serviceCommission: 0,
});

// 表单验证规则
const formRules = {
  type: [{ required: true, message: '请输入次卡类型', trigger: 'blur' }],
  salesCommission: [
    { required: true, message: '请输入销售提成', trigger: 'blur' },
    {
      type: 'number',
      min: 0,
      max: 100,
      message: '销售提成必须在0-100之间',
      trigger: 'blur',
    },
  ],
  serviceCommission: [
    { required: true, message: '请输入服务提成', trigger: 'blur' },
    { type: 'number', min: 0, message: '服务提成不能为负数', trigger: 'blur' },
  ],
};

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const modalTitle = computed(() => {
  return props.card ? `修改次卡(${props.card.type})` : '添加次卡';
});

// 方法
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const cardData = {
      ...formData,
      id: props.card?.id,
    };

    emit('save', cardData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
  resetForm();
};

const resetForm = () => {
  formData.type = '';
  formData.salesCommission = 0;
  formData.serviceCommission = 0;
  formRef.value?.resetFields();
};

// 监听props变化，初始化表单数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      if (props.card) {
        // 编辑模式，填充现有数据
        Object.assign(formData, {
          ...props.card,
        });
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    }
  },
);
</script>

<template>
  <a-modal
    v-model:open="visible"
    :title="modalTitle"
    width="500px"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="次卡类型" name="type" required>
        <a-input
          v-model:value="formData.type"
          placeholder="请输入次卡类型"
          size="large"
        />
      </a-form-item>
      <a-form-item label="销售提成" name="salesCommission" required>
        <div class="commission-input-container">
          <a-input-number
            v-model:value="formData.salesCommission"
            placeholder="请输入0-100之间数字"
            size="large"
            style="width: 100%"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
          />
          <div class="commission-help">
            <span class="help-text">填写数字对应提成百分比</span>
            <a-tooltip
              title="销售提成说明：填写0-100之间的数字，表示提成的百分比"
            >
              <a-icon type="question-circle" class="help-icon" />
            </a-tooltip>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="服务提成" name="serviceCommission" required>
        <div class="commission-input-container">
          <a-input-number
            v-model:value="formData.serviceCommission"
            placeholder="请输入服务提成金额"
            size="large"
            style="width: 100%"
            :min="0"
            :precision="2"
            :step="0.5"
          />
          <div class="commission-help">
            <span class="help-text">填写服务提成金额(元)</span>
            <a-tooltip
              title="服务提成说明：每次服务完成后，服务人员获得的固定提成金额"
            >
              <a-icon type="question-circle" class="help-icon" />
            </a-tooltip>
          </div>
        </div>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="saving" @click="handleSave">
          保存
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<style scoped>
.commission-input-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.commission-help {
  display: flex;
  align-items: center;
  gap: 8px;
}

.help-text {
  font-size: 12px;
  color: #666;
}

.help-icon {
  color: #1890ff;
  cursor: pointer;
}
</style>
